import request from '@/utils/request'
import type { ApiResponse } from '@/types/api'

// 系统监控相关接口类型定义
export interface SystemInfo {
  cpuUsage: number
  cpuCores: number
  totalMemory: number
  usedMemory: number
  memoryUsage: number
  jvmVersion: string
  jvmUptime: number
  jvmMemoryUsage: JvmMemoryUsage
  diskInfos: DiskInfo[]
  cacheStats: Record<string, any>
  timestamp: string
}

export interface JvmMemoryUsage {
  used: number
  max: number
  committed: number
  usage: number
}

export interface DiskInfo {
  path: string
  total: number
  used: number
  free: number
  usage: number
}

export interface BusinessStatistics {
  totalUsers: number
  activeUsers: number
  onlineUsers: number
  permissionUsageStats: Record<string, number>
  roleDistribution: Record<string, number>
  tenantStats: TenantStatistics
  apiCallStats: Record<string, number>
  timestamp: string
}

export interface TenantStatistics {
  totalTenants: number
  activeTenants: number
  tenantUserCounts: Record<string, number>
}

export interface TenantIsolationMetrics {
  tenantCacheKeyCount: Record<string, number>
  tenantCacheHitRate: Record<string, number>
  crossTenantLeakageWarnings: string[]
  globalCacheKeyCount: number
  formatCompliance: CacheKeyFormatCompliance
  timestamp: string
}

export interface CacheKeyFormatCompliance {
  overallCompliance: number
  formatViolations: Record<string, number>
  commonIssues: string[]
}

export interface CacheKeyValidationReport {
  totalKeys: number
  validKeys: number
  invalidKeys: number
  complianceRate: number
  invalidKeyExamples: string[]
  recommendations: string[]
  reportTime: string
}

// 系统监控API
export const systemMonitorApi = {
  // 获取系统信息监控（使用新的监控接口，返回数字格式）
  getSystemInfo: (): Promise<ApiResponse<SystemInfo>> => {
    return request.get('/monitor/system-resources')
  },

  // ❌ 已删除：业务统计接口已迁移
  // 新接口：userStatisticsApi.getBusinessStatistics()
  // getBusinessStats: (): Promise<ApiResponse<BusinessStatistics>> => {
  //   return request.get('/monitor/business-stats')  // 已迁移至 /user/statistics
  // },

  // 获取租户隔离监控
  getTenantIsolationMetrics: (): Promise<ApiResponse<TenantIsolationMetrics>> => {
    return request.get('/monitor/tenant-isolation')
  },

  // 获取缓存键格式验证报告
  getCacheKeyValidationReport: (): Promise<ApiResponse<CacheKeyValidationReport>> => {
    return request.get('/monitor/cache-key-validation')
  },

  // 获取系统健康检查
  getSystemHealth: (): Promise<ApiResponse<Record<string, any>>> => {
    return request.get('/monitor/health')
  },

  // 获取监控仪表板数据
  getDashboardData: (): Promise<ApiResponse<Record<string, any>>> => {
    return request.get('/monitor/dashboard')
  }
}

// 缓存监控API
export const cacheMonitorApi = {
  // 获取缓存统计
  getCacheStats: (cacheType?: string): Promise<ApiResponse<Record<string, any>>> => {
    const params = cacheType ? { cacheType } : {}
    return request.get('/monitor/cache-stats', { params })
  },

  // 获取缓存总体统计
  getOverallStatistics: (): Promise<ApiResponse<any>> => {
    return request.get('/cache/monitor/statistics')
  },

  // 获取热点键统计
  getHotKeys: (limit = 20): Promise<ApiResponse<any[]>> => {
    return request.get('/cache/monitor/hot-keys', { params: { limit } })
  },

  // 获取缓存健康状态
  getCacheHealth: (): Promise<ApiResponse<any>> => {
    return request.get('/cache/monitor/health')
  },

  // 获取缓存性能报告
  getPerformanceReport: (timeRange = '1h'): Promise<ApiResponse<any>> => {
    return request.get('/cache/monitor/performance', { params: { timeRange } })
  },

  // 清理缓存
  clearCache: (pattern?: string): Promise<ApiResponse<void>> => {
    return request.post('/cache/monitor/clear', { pattern })
  },

  // 刷新缓存
  refreshCache: (): Promise<ApiResponse<void>> => {
    return request.post('/cache/monitor/refresh')
  },

  // 重置统计数据
  resetStatistics: (): Promise<ApiResponse<void>> => {
    return request.post('/cache/monitor/reset')
  }
}

// 安全日志API
export const securityLogApi = {
  // 分页查询安全日志
  querySecurityLogs: (params: {
    current: number
    size: number
    userId?: string
    operation?: string
    startTime?: string
    endTime?: string
  }): Promise<ApiResponse<any>> => {
    return request.get('/security-logs', { params })
  },

  // 获取安全日志详情
  getSecurityLogDetail: (logId: string): Promise<ApiResponse<any>> => {
    return request.get(`/security-logs/${logId}`)
  },

  // 获取安全日志统计
  getSecurityLogStatistics: (timeRange?: string): Promise<ApiResponse<any>> => {
    return request.get('/security-logs/statistics', { 
      params: timeRange ? { timeRange } : {} 
    })
  },

  // 导出安全日志
  exportSecurityLogs: (params: {
    userId?: string
    operation?: string
    startTime?: string
    endTime?: string
  }): Promise<ApiResponse<any>> => {
    return request.get('/security-logs/export', { 
      params,
      responseType: 'blob'
    })
  }
}

// 安全监控API（新增）
export const securityMonitorApi = {
  // 获取IP访问统计
  getIpStatistics: (hours = 24): Promise<ApiResponse<any[]>> => {
    return request.get('/security-monitor/ip-statistics', { params: { hours } })
  },

  // 获取权限访问统计
  getPermissionStatistics: (hours = 24): Promise<ApiResponse<any>> => {
    return request.get('/security-monitor/permission-statistics', { params: { hours } })
  },

  // 获取安全建议
  getSecurityRecommendations: (): Promise<ApiResponse<any[]>> => {
    return request.get('/security-monitor/security-recommendations')
  },

  // 获取安全事件详细分析
  getSecurityEventsAnalysis: (days = 7): Promise<ApiResponse<any>> => {
    return request.get('/security-monitor/security-events-analysis', { params: { days } })
  },

  // 获取安全趋势数据
  getSecurityTrends: (days = 30): Promise<ApiResponse<any>> => {
    return request.get('/security-monitor/security-trends', { params: { days } })
  }
}

// 用户业务统计API（新增）
export const userStatisticsApi = {
  // 获取综合业务统计
  getBusinessStatistics: (): Promise<ApiResponse<any>> => {
    return request.get('/user/statistics')
  },

  // 获取用户概览统计
  getUserOverview: (): Promise<ApiResponse<any>> => {
    return request.get('/user/overview')
  },

  // 获取角色分布统计
  getRoleDistribution: (): Promise<ApiResponse<Record<string, number>>> => {
    return request.get('/user/role-distribution')
  },

  // 获取租户统计数据
  getTenantStatistics: (): Promise<ApiResponse<any>> => {
    return request.get('/user/tenant-statistics')
  }
}

// 默认导出
export default {
  systemMonitor: systemMonitorApi,
  cacheMonitor: cacheMonitorApi,
  securityLog: securityLogApi,
  securityMonitor: securityMonitorApi,
  userStatistics: userStatisticsApi  // 新增用户统计API
}
